<!--
 * @Descripttion:
 * @version:
 * @Author: cxguo
 * @Date: 2020-03-10 20:49:27
 * @LastEditors: cxguo
 * @LastEditTime: 2020-11-12 15:03:49
 -->
<template>
  <el-cascader
    v-model="insideValue"
    expand-trigger="hover"
    :options="optionsTreeData"
    v-bind="$attrs"
    @change="onChange"
  />
</template>
<script>
import { optionsTree } from '@/api/bsd/account.js'
import XEUtils from 'xe-utils'
import store from '@/store'

export default {
  props: {
    value: {
      type: Array,
      default: () => { return [] }
    },
    /**
     * 自动设置当前值
     */
    autoCurrent: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      insideValue: [],
      optionsTreeData: [],
      optionsData: [],
      appData: store.getters.appData
    }
  },
  watch: {
    'value': {
      handler(val) {
        if (val) this.insideValue = val
      },
      immediate: true
    }
  },
  created() {
    this.getListData()
  },
  methods: {
    getListData(keywords = '') {
      optionsTree({ keywords }).then(res => {
        if (res.data.flag) {
          const data = res.data.data || []
          let treeData = XEUtils.toArrayTree(data, {
            key: 'value',
            parentKey: 'pid'
          })
          this.optionsData = data
          treeData = this.removeBlankChilrenData(treeData)
          this.optionsTreeData = treeData
          this.autoCurrent && this.handleCurrentValue(treeData)
        }
      })
    },
    handleCurrentValue(treeData) {
      const value = []
      treeData.forEach(item => {
        const children = item.children || []
        if (children.length === 0) {
          this.insideValue = []
          this.onChange([])
          return
        }
        const defaultObj = children.find(item => { return item.isDefault === '1' })
        if (defaultObj) {
          value.push(defaultObj.value)
        } else {
          const store = children[0]
          value.push(store.value)
        }
      })
      this.insideValue = value
      this.onChange(value)
    },
    removeBlankChilrenData(treeData) {
      treeData.forEach(item => {
        const children = item.children || []
        if (children.length === 0) {
          this.$delete(item, 'children')
        } else {
          this.removeBlankChilrenData(children)
        }
      })
      return treeData
    },
    onChange(data) {
      this.$emit('change', data)
      this.$emit('input', data)
    }
  }
}
</script>
